package school30.ui.forms;

import school30.KeyboardHandler;
import school30.TextHandler;
import school30.ui.Painter;

public class TextField extends Widget {

    private Runnable action;
    private int background = 0x0000ff;
    private int foreground = 0xffffff;
    private int borderColor = 0xffff00;
    private int activeBorderColor = 0xff0000;
    private boolean toogle;
    private boolean focused;
    private String text = "Edit me";
    private KeyboardHandler keyboardHandler = new KeyboardHandler();

    public TextField() {
        focusable = true;
        keyboardHandler.initDefault();
        keyboardHandler.setTextHandler(new TextHandler()  {

            public void handleCharEnter(char c) {
                text += c;
                getForm().repaint();
            }
        });
    }

    public void keyPressed(int code) {
        keyboardHandler.keyPressed(code);
    }

    public void keyReleased(int code) {
        keyboardHandler.keyReleased(code);
    }

    public void paint(Painter p) {
        p.setColor(background);
        p.fillRectangle(0, 0, position.getWidth(), position.getHeight());
        p.setColor(foreground);
        p.drawString(text, position.getWidth() / 2, position.getHeight() / 2, Painter.BASELINE | Painter.HCENTER);
        if (!focused) {
            p.setColor(borderColor);
        } else {
            p.setColor(activeBorderColor);
        }
        p.drawLine(0, position.getHeight() - 1, 0, 0);
        p.drawLine(position.getWidth() - 1, 0, 0, 0);
        p.drawLine(0, position.getHeight() - 1, position.getWidth() - 1, position.getHeight() - 1);
        p.drawLine(position.getWidth() - 1, 0, position.getWidth() - 1, position.getHeight() - 1);
    }

    public void focusGained() {
        focused = true;
        getForm().repaintWidget(this);
    }

    public void focusLosed() {
        focused = false;
        getForm().repaintWidget(this);
    }

    public Runnable getAction() {
        return action;
    }

    public void setAction(Runnable action) {
        this.action = action;
    }

    public int getBackground() {
        return background;
    }

    public void setBackground(int background) {
        this.background = background;
    }

    public int getBorderColor() {
        return borderColor;
    }

    public void setBorderColor(int borderColor) {
        this.borderColor = borderColor;
    }

    public int getForeground() {
        return foreground;
    }

    public void setForeground(int foreground) {
        this.foreground = foreground;
    }

    public boolean isToogle() {
        return toogle;
    }

    public void setToogle(boolean toogle) {
        this.toogle = toogle;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}
